<template>
	<view class="content">
		<view class="main-content" v-show="!isSuccess">
			<view class="content-title"><text>商家收款</text></view>
			<image :src="headImg" class="eName"></image>
			<text class="cName">{{ mchName }}</text>
			<view class="buy-count">
				<picker @change="pay_methods_switch" :value="pay_index" :range="pay_methods" style="color:#2973E3">
					<view class="uni-input" style="font-size:36upx;">请选择支付方式:{{ pay_methods[pay_index] }}</view>
				</picker>
				<label class="num" for="pay_money" style="color:#444444; font-size: 38upx;">支付金额</label>
				<input id="pay_money" type="digit" v-model="money" class="num_" placeholder="请输入支付金额" style="color:#444444;" />
			</view>
			<button class="confirm-btn" @tap="pay" :disabled="isDisable">确认支付</button>
		</view>
		<uni-password ref="secrity" @input="onInput" @confirm="onConfirms" @back="paymentPasswordBack" v-if="pay_pass_display">请输入6位支付密码</uni-password>
		<view class="success" v-show="isSuccess">
			<view class="success_title">支付成功</view>
			<view class="success_money">￥{{ money }} 元</view>
		</view>
	</view>
</template>

<script>
import uniPassword from '@/components/ku3gitxdx-payment-password/ku3gitxdx-payment-password.vue';
import uniIcon from '@/components/uni-icon/uni-icon.vue';
import eonfox from '@/components/eonfox/eonfox.js';
import fns from '@/components/eonfox/fns.js';
import order from '@/components/eonfox/order.js';
import websocketObject from '@/components/eonfox/websocket.js';
var ef = new eonfox();
var websockets = new websocketObject();
export default {
	data() {
		return {
			mchName: '未设置',
			headImg: '../../static/wode.png',
			qiniu: '',
			code: '',
			pay_method: 'money', //支付方式 weixinpay 微信支付、alipay 支付宝支付,money 余额支付
			money: '',
			mch_id: '',
			cashier_user_id: '', //user_id
			isDisable: false,
			isDisablePaymentPassword: false, //是否支付密码按钮已点击
			pay_methods: [
				'预付款支付',
				'微信支付',
				// #ifdef APP-PLUS
				'支付宝支付'
				// #endif
			],
			pay_index: 0,
			pay_pass_display: false,
			pay_pass: '',
			password: '',
			paymentPasswordDispaly: true,
			isSuccess: false
		};
	},
	components: { uniIcon, uniPassword },
	onLoad(option) {
		console.log('option', option);
		this.mch_id = option.mch_id;
		if (option.user_id) {
			this.cashier_user_id = option.user_id;
		} else {
			this.cashier_user_id = '';
		}

		this.getUserInfo(this.mch_id);
	},
	methods: {
		back() {
			console.log('支付返回');
			uni.navigateBack({
				delta: 1
			});
		},
		//切换支付方式
		pay_methods_switch(e) {
			var index = e.target.value;
			console.log('支付方式:', typeof index, '-', index);
			this.pay_index = index; //以选择序号省显示改变
			//切换支付方式
			switch (index) {
				case '0':
					this.pay_method = 'money';
					this.pay_pass_display = false;
					break;
				case '1':
					this.pay_method = 'weixinpay';
					this.pay_pass_display = false;
					break;
				case '2':
					this.pay_method = 'alipay';
					this.pay_pass_display = false;
					break;
			}
			console.log('当前支付方式:', this.pay_method, '-->', this.pay_methods[index]);
		},
		pay() {
			var _this = this;
			console.log('开始支付', _this.isDisable);
			// 				uni.showLoading({
			// 					title:'正在支付'
			// 				})
			if (_this.isDisable) {
				uni.showToast({
					title: '请勿重复操作',
					icon: 'none'
				});
				return;
			}
			if (!_this.money) {
				return;
			}
			_this.isDisable = true;
			switch (_this.pay_method) {
				case 'money':
					// _this.pay_money()
					//_this.onConfirms;
					_this.pay_pass_display = true; //显示
					// _this.pay_password();//支付密码
					break;
				case 'weixinpay':
					// #ifdef MP-WEIXIN
					_this.pay_mp_weixin();
					// #endif
					// #ifdef APP-PLUS
					_this.pay_app_weixin();
					// #endif
					break;
				case 'alipay':
					// #ifdef APP-PLUS
					_this.payAli();
					// #endif
					break;
				default:
					break;
			}
		},
		pay_password() {
			this.pay_pass_display = true;
		},
		onInput(e) {
			//e.cancel = true;
			//console.log('onInput',e,e.cancel);
		},
		/* onConfirm(e) {
				let password = e.value;
				this.pay_pass_display=password
				console.log('password',password);
				this.pay_pass_display=false
			}, */
		//余额支付
		pay_money(password, error_call_back) {
			if (!error_call_back || typeof error_call_back != 'function') {
				error_call_back = function() {};
			}
			var _this = this;
			uni.showLoading({
				title: '正在支付'
			});
			ef.submit({
				request: {
					s: [
						'MERCHANTMONEYSELFPAYMENT',
						[
							{
								merchant_id: _this.mch_id,
								money_fen: _this.money * 100,
								comment: _this.money,
								pay_password: password,
								pay_method:'user_money',
								action_user_id:_this.cashier_user_id,
							}
						]
					]
				},
				callback: function(data) {
					if (
						fns.checkError(data, 's', function(errno, error) {
							error_call_back(); //出错回调
							_this.isDisable = false;
							uni.showToast({
								title: error,
								icon: 'none'
							});
						})
					) {
						_this.websocketMessage();
						uni.showToast({
							title: '支付成功',
							icon: 'success',
							success() {
								_this.isSuccess = true;
								_this.pay_pass_display = false;
							}
						});
					}
					//_this.isDisable=false
				},
				error: function(err) {
					error_call_back(); //出错回调
					_this.isDisable = false;
					uni.showToast({
						title: JSON.stringify(err),
						duration: '2000'
					});
				}
			});
		},

		paymentPasswordBack(e) {
			console.log('支付密码点击了返回，进来了', e);
			this.isDisablePaymentPassword = false;
			this.isDisable = false;
			this.pay_pass_display = false;
		},
		onConfirms(e) {
			var _this = this;

			if (_this.isDisablePaymentPassword) {
				return false;
			}

			let password = e.value;
			console.log('password', password, password.length);
			if (password.length != 6) {
				fns.err('请正确输入密码');
			} else {
				_this.isDisablePaymentPassword = true;
				_this.pay_money(password, function() {
					_this.isDisablePaymentPassword = false;
				});
				// 						fns.success('支付成功',function(){
				// 							uni.showToast({
				// 								title:'支付成功',
				// 								icon:'none',
				// 								success() {
				// 									setTimeout(function(){
				// 										_this.pay_pass_display=false
				// 										uni.reLaunch({
				// 											url:'./shoppingCar'
				// 										})
				// 									},2000)
				// 								}
				// 							})
				//
				// 						})
			}
			// this.pay_pass_display=false
		},
		// 			pay(id,method){
		// 				var _this=this
		// 				console.log('pay()',id,method);
		// 				switch (method){
		// 					case 'user_money':
		// 					uni.showToast({
		// 						title:'请输入支付密码',success() {
		// 							console.log('tj');
		// 							_this.pay_pass_display=true
		// 							_this.order_id=id.shop_order_id,
		// 							_this.order_method=method
		// 						}
		// 					})
		//
		// 						break;
		// 					case 'alipay':
		// 					fns.err('支付未完善')
		// 						break;
		// 					case 'weixinpay':
		// 					fns.err('支付未完善')
		// 						break;
		// 				}
		// 			},
		payAli() {
			var _this = this;
			ef.submit({
				request: {
					s: [
						'MERCHANTMONEYSELFPAYMENT',
						[
							{
								merchant_id: _this.mch_id, //商家id
								credit_number: _this.credit_number, //积分数量
								money_fen: _this.money * 100,
								pay_method: 'alipay', //支付方式 weixinpay 微信支付、alipay 支付宝支付
								alipay_trade_type: 'APP',
								action_user_id:_this.cashier_user_id,
								
							}
						]
					]
				},
				callback(data) {
					console.log('调起支付宝支付', data);

					fns.checkError(data, 's', function(errno, error) {
						uni.showToast({
							title: error,
							icon: 'none'
						});
					});
					var ali = data.data.s.data.alipay;
					if (ali) {
						uni.requestPayment({
							provider: 'alipay',
							orderInfo: ali,
							success: function(res) {
								console.log('success:' + JSON.stringify(res));
								uni.showToast({
									title: '支付成功',
									success() {
										setTimeout(function() {
											_this.websocketMessage();
											uni.hideToast();
											uni.reLaunch({
												url: '../../pages/index/index'
											});
										}, 1500);
									}
								});
							},
							fail: function(err) {
								console.log('fail:' + JSON.stringify(err));
							}
						});
					}
				},
				error(err) {
					fns.err('提交订单失败', err, 1);
				}
			});
		},
		pay_mp_weixin() {
			var _this = this;
			wx.login({
				//微信小程序登录获取code
				success(res) {
					_this.code = res.code;
					if (res.code) {
						//获取到code生成订单
						// 发起网络请求
						console.log('发起网络请求');
						ef.submit({
							request: {
								s: [
									'MERCHANTMONEYSELFPAYMENT',
									[
										{
											merchant_id: _this.mch_id, //商家id
											weixin_login_code: res.code,
											money_fen: _this.money * 100, //支付金额（分)
											pay_method: 'weixinpay', //支付方式 weixinpay 微信支付、alipay 支付宝支付
											weixin_trade_type: 'JSAPI',
											action_user_id:_this.cashier_user_id,
										}
									]
								]
							},
							callback: function(data) {
								_this.isDisable = false;
								console.log('商家', data);
								if (
									fns.checkError(data, 's', function(erron, error) {
										_this.isDisable = false;
										uni.showToast({
											title: error,
											icon: 'none'
										});
									})
								) {
									//7,已支付
									//发起支付
									console.log('发起支付', data.data.s.data);
									_this.requestPayment(data.data.s.data);
									//获取成功，无错误信息时
								}
							},
							error: function(err) {
								_this.isDisable = false;
								console.log('出错啦', err);
								uni.showToast({
									title: JSON.stringify(err),
									icon: 'none'
								});
							}
						});
					} else {
						_this.isDisable = false;
						console.log('登录失败！' + res.errMsg);
						uni.showToast({
							title: '登录失败！' + res.errMsg,
							icon: 'none'
						});
					}
				}
			});
		},
		pay_app_weixin() {
			var _this = this;
			uni.showLoading({
				title: '正在支付'
			});
			console.log('支付开始');
			ef.submit({
				request: {
					s: [
						'MERCHANTMONEYSELFPAYMENT',
						[
							{
								merchant_id: _this.mch_id, //商家id
								money_fen: _this.money * 100, //支付金额（分
								pay_method: 'weixinpay', //支付方式 weixinpay 微信支付、alipay 支付宝支付
								weixin_trade_type: 'APP',
								action_user_id:_this.cashier_user_id,
							}
						]
					]
				},
				callback: function(data) {
					uni.hideLoading();
					_this.isDisable = true;
					console.log('订单获取回调', JSON.stringify(data));
					if (
						fns.checkError(data, 's', function(erron, error) {
							_this.isDisable = false;
							uni.showToast({
								title: error,
								icon: 'none'
							});
						})
					) {
						//7,已支付
						//发起支付
						console.log('发起支付', data.data.s.data);
						_this.requestPayment(data.data.s.data);
						//获取成功，无错误信息时
						_this.isDisable = false;
					}
				},
				error: function(err) {
					_this.isDisable = false;
					console.log('出错啦', err);
					uni.showToast({
						title: JSON.stringify(err),
						icon: 'none'
					});
					uni.hideLoading();
				}
			});
		},
		requestPayment(wxArr) {
			// #ifdef APP-PLUS
			var orderInfo = {
				appid: wxArr.appid,
				partnerid: wxArr.mch_id, //商户号
				prepayid: wxArr.prepay_id, //预支付交易会话ID
				package: 'Sign=WXPay', //扩展字段,暂填写固定值Sign=WXPay
				noncestr: wxArr.nonce_str, //随机字符串
				timestamp: wxArr.time_stamp, //时间戳
				sign: wxArr.pay_sign //签名
			};
			// #endif
			var _this = this;
			//	console.log('支付参数',wxArr);console.log('时间戳',String(Date.now()));
			uni.requestPayment({
				// #ifdef MP-WEIXIN
				provider: 'wxpay',
				timeStamp: String(wxArr.time_stamp),
				nonceStr: wxArr.nonce_str,
				package: 'prepay_id=' + wxArr.prepay_id,
				signType: wxArr.sign_type,
				paySign: wxArr.pay_sign,
				// #endif

				// #ifdef APP-PLUS
				provider: 'wxpay',
				orderInfo: JSON.stringify(orderInfo),
				// #endif

				success: function(res) {
					console.log('支付成功success:' + JSON.stringify(res));
					if (res.errMsg == 'requestPayment:ok') {
						//支付成功是进行订单查询
						var out_time = 0;
						uni.showToast({
							title: '正在查询支付结果',
							icon: 'loading'
						});
						//检查订单支付情况
						order.checkPayState({
							order_id: wxArr.order_id, 
							success:function(){
								
								uni.showToast({
									title: '支付成功'
								});
								
								_this.websocketMessage();
								setTimeout(function() {
									uni.hideToast();
									uni.reLaunch({
										url: '../../pages/index/index'
									});
								}, 1500);
							},
							fail:function(){
								uni.showToast({
									title: '业务超时，如已支付，请稍后再个人页面查看是否到账',
									icon: 'none'
								});
							}
						});
						
						/* var timeTn = setInterval(function() {
							out_time++;
							if (out_time <= 30) {
								_this.order_query(wxArr.order_id, function() {
									clearInterval(timeTn);
									uni.showToast({
										title: '购买成功',
										icon: 'none'
									});
									_this.websocketMessage();
									setTimeout(function() {
										uni.hideToast();
										uni.reLaunch({
											url: '../../pages/index/index'
										});
									}, 1500);
								});
							} else {
								uni.showToast({
									title: '业务超时，如已支付，请稍后再个人页面查看是否到账',
									icon: 'none'
								});
								clearInterval(timeTn);
								// setTimeout(function() {
								// 	uni.hideToast();
								// }, 1500);
							}
						}, 1000); */
					} else {
						uni.showToast({
							title: '业务超时，如已支付，请稍后再个人页面查看是否到账',
							icon: 'none'
						});
						// setTimeout(function() {
						// 	uni.hideToast();
						// }, 1500);
					}
				},
				fail: function(err) {
					return false;
				}
			});
		},
		switcher_pay: function() {
			uni.showToast({
				title: '暂不支持支付功能的切换'
			});
		},
		//支付结果查询
		order_query(order_id, fun) {
			console.log('正在查询');
			ef.submit({
				request: {
					s: [
						'APPLICATIONORDERSELFPAYSTATE',
						[
							{
								order_id: order_id
							}
						]
					]
				},
				callback: function(data) {
					// console.log('支付查询回调成功',data.data.s.data) ;return data.data.s.data;
					if (!data.errno && !data.data.s.errno) {
						//获取成功，无错误信息时
						if (data.data.s.data) {
							fun();
						} else {
							return 0;
						}
					} else {
						return 0;
					}
				},
				error: function(err) {
					return 0;
				}
			});
		},
		getUserInfo(mch_id) {
			console.log('getUserInfo  ：  star');
			var _this = this;
			ef.submit({
				request: { config: ['APPLICATIONCONFIG'], mch: ['MERCHANTGET', [{ merchant_id: mch_id, lon: 0, lat: 0 }]] },
				callback(data) {
					var re = fns.checkError(data, ['config', 'mch'], function(errno, error) {
						uni.showToast({
							title: error,
							icon: 'none'
						});
					});
					console.log('qiniu && mch : ', re);
					if (re.config && re.config.qiniu_domain) {
						_this.qiniu = re.config.qiniu_domain;
					}
					if (re.mch) {
						_this.mchName = re.mch.name;
						_this.headImg = _this.qiniu + re.mch.logo_image_id;
					}
					console.log('qiniu && mch : ', re);
				}
			});
		},

		websocketMessage: function() {
			var that=this
			var meg = '商家收款已到账，' + that.money + '元';
			//var meg = '商家收款已到账，' + that.money + '元';
			console.log('1111111提醒商家收款成功1111111', that.cashier_user_id, meg);
			websockets.user_push(that.cashier_user_id, {
				type:'商家收款提醒',
				content:meg
			}, function(err){
				//提醒失败
				console.log('！！！！！！提醒商家收款失败！！！！！', err);
			});
		}
	}
};
</script>
<style>
.logo {
	height: 200upx;
	width: 200upx;
	margin-top: 200upx;
}
.title {
	font-size: 36upx;
	color: #8f8f94;
}
.success {
	width: 100%;
	height: 100vh;
	background-color: #ffffff;
}
.success_title {
	width: 100%;
	height: 130upx;
	font-size: 70upx;
	color: #00b26a;
	text-align: center;
}
.success_money {
	width: 100%;
	height: 100upx;
	font-size: 60upx;
	margin-top: 50upx;
	text-align: center;
}
</style>
<style scoped lang="stylus" ref="stylesheet/stylus">
.content
	width 100%
	margin-top 70upx
	background-color #fff
	.title-box
		width 100%
		height 60px
		padding-left 15px
		line-height 60px
		background #fff
		border-bottom 1px solid #ccc
		.icon
			margin-top -5px

	.main-content
		width calc(90% - 2upx)
		height 460px
		margin 0 auto
		background-color #fff
		border-right 1upx solid #ccc
		border-left 1upx solid #ccc
		border-bottom 1px solid #ccc
		.content-title
			width calc(100% - 20upx)
			height 60px
			margin 20px 0
			line-height 60px
			color #fff
			padding-left 20upx
			background-color green
		.eName
			background-color #fff
			display block
			width 120px
			height 120px
			line-height 120px
			font-size 28px
			color #fff
			text-align center
			margin 0 auto
			border-radius 50%
			border 1px solid #ccc
			background-color orange
		.cName
			display block
			font-size 34upx
			width 100%
			height 40upx
			color #333
			margin 10upx auto
			text-align center
		.img
			width 140px
			margin 0 auto
			image
				width 140px
				height 140px
		.find
			display block
			width 100%
			text-align center
			margin 10px
			font-size 14px
	.buy-count
		width 95%
		height 30%
		color #ccc
		margin 0 auto
		font-size 24upx
		display flex
		justify-content center   // 水平居中
		align-items center       // 垂直居中
		flex-direction column
		border-bottom 1px solid #ccc
		text-align left !important

		.num
			width 100%
			height 33%
			line-height 40px
			display block
			color #00000
			font-size 30upx
		.num_
			width 99%
			height 90upx
			line-height 80px
			font-size 30upx
			display block
			background-color #eee
			border-radius 15upx
			padding-left 1%
	.confirm-btn
		width 95%
		height 55px
		color #fff
		margin 0 auto
		display flex
		justify-content center   // 水平居中
		align-items center
		background-color #F8A0A0
		border-radius 4px
</style>
